package com.example.chamberlainserver.controller;

import com.example.chamberlainserver.Entry.UserLoginLog;
import com.example.chamberlainserver.Service.UserLogService;
import com.example.chamberlainserver.Vo.Response.ApiResponse;
import com.example.chamberlainserver.dto.PageResult;
import com.example.chamberlainserver.dto.UserLoginLogQueryDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 用户登录日志控制器
 */
@RestController
@RequestMapping("/logs/login")
public class UserLoginLogController {
    
    @Autowired
    private UserLogService userLogService;
    
    /**
     * 分页查询登录日志
     * @param queryDTO 查询条件
     * @return 分页结果
     */
    @PostMapping("/page")
    public ResponseEntity<ApiResponse<PageResult<UserLoginLog>>> pageLoginLogs(@RequestBody UserLoginLogQueryDTO queryDTO) {
        PageResult<UserLoginLog> pageResult = userLogService.pageLoginLogs(queryDTO);
        return ResponseEntity.ok(ApiResponse.success("查询登录日志成功", pageResult));
    }
    
    /**
     * 获取登录统计数据
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return 登录统计数据
     */
    @GetMapping("/stats")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getLoginStats(
            @RequestParam(required = false) LocalDateTime startTime,
            @RequestParam(required = false) LocalDateTime endTime) {
        // 如果未指定时间范围，默认查询最近30天
        if (startTime == null) {
            startTime = LocalDateTime.now().minusDays(30);
        }
        if (endTime == null) {
            endTime = LocalDateTime.now();
        }
        
        Map<String, Object> stats = userLogService.getLoginStats(startTime, endTime);
        return ResponseEntity.ok(ApiResponse.success("获取登录统计数据成功", stats));
    }
    
    /**
     * 获取每日登录次数
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return 每日登录次数
     */
    @GetMapping("/daily-counts")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getDailyLoginCounts(
            @RequestParam(required = false) LocalDateTime startTime,
            @RequestParam(required = false) LocalDateTime endTime) {
        // 如果未指定时间范围，默认查询最近30天
        if (startTime == null) {
            startTime = LocalDateTime.now().minusDays(30);
        }
        if (endTime == null) {
            endTime = LocalDateTime.now();
        }
        
        List<Map<String, Object>> dailyCounts = userLogService.getDailyLoginCounts(startTime, endTime);
        return ResponseEntity.ok(ApiResponse.success("获取每日登录次数成功", dailyCounts));
    }
}